package cn.edu.wfit.modules.directionmanagement.util;

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import java.io.IOException;
/**
 * 问答功能
 */
@Slf4j
@Component
public class RequestAskUtil {
    @Value("${dashscope.api-key}")
    private String apiKey;
    public ResponseBodyEmitter ask(String inputValue) throws IOException, NoApiKeyException, InputRequiredException {

        ResponseBodyEmitter emitter = new ResponseBodyEmitter(-1L); // 无限超时
        // 设置响应头
        emitter.send("\n"); // 发送一个初始换行符以启动连接
        ApplicationParam param = ApplicationParam.builder()
                .apiKey(apiKey)//主机的apikey
                .appId("3b987617463e4e8b9bf67ce169771ad2")//智能体应用id,后续需要调教一个优秀的智能体
                .prompt(inputValue)//prompt提示词
                .incrementalOutput(true)//是否使用流式输出,我记得是这个功能来着,有些忘记了
                .build();
        Application application = new Application();
        Flowable<ApplicationResult> result = application.streamCall(param);
        result.subscribe(
                 data -> {
                    try {
                        String text = data.getOutput().getText();
                        emitter.send(text);
                        System.out.println(text);
                    } catch (IOException e) {
                        emitter.completeWithError(e);
                    }
                },
                error -> {
                    emitter.completeWithError(error);
                },
                () -> {
                    try {
                        emitter.send("[DONE]");
                        emitter.complete();
                    } catch (IOException e) {
                        emitter.completeWithError(e);
                    }
                }
        );
        return emitter;
    }
}
